package com.example.plant.util.images;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;

import androidx.activity.result.ActivityResultCaller;
import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.function.Consumer;

@SuppressWarnings("unused")
public class RegisterActivityForResultUtil {

    private static final String TAG = "RegisterActivityForRs";

    @RequiresApi(api = Build.VERSION_CODES.N)
    public static ActivityResultLauncher<Bundle> registerForCameraCaptureResult(Context context, Consumer<BitmapBundle> fallbackAction) {
        // 准备临时文件
        File tmp = new File(context.getCacheDir(), "tmp.jpg");
        if (tmp.exists()) {
            //noinspection ResultOfMethodCallIgnored
            tmp.delete();
        }

        // 用于接收从相机拍摄的照片
        Uri imageUri = getImageUri(context, tmp);

        // 注册相机启动与结果回调
        return ((ActivityResultCaller) context).registerForActivityResult(new ResultContract(ResultContract.CAMERA_CAPTURE, imageUri), result -> {
            Log.e(TAG, "相机调用返回啦");
            Bitmap bitmap = null;
            try {
                bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUri));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (bitmap != null) {
                fallbackAction.accept(new BitmapBundle(tmp.getPath(), bitmap));
            }
        });
    }

    @SuppressLint("ObsoleteSdkInt")
    private static Uri getImageUri(Context context, File tmp) {
        Uri imageUri;
        /*
         * 7.0系统开始，直接使用本地真实路径的Uri被认为是不安全的，会抛 出一个FileUriExposedException异常。
         *  而FileProvider则是一种特殊的内容提供器，它使用了和内 容提供器类似的机制来对数据进行保护，
         *  可以选择性地将封装过的Uri共享给外部，从而提高了 应用的安全性
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //大于等于版本24（7.0）的场合
            imageUri = FileProvider.getUriForFile(context, "com.example.plant.fileprovider", tmp);
        } else {
            //小于android 版本7.0（24）的场合
            imageUri = Uri.fromFile(tmp);
        }
        return imageUri;
    }

    public static ActivityResultLauncher<Bundle> registerForPictureSelectResult(Context context, Consumer<BitmapBundle> fallbackAction) {
        // 注册相册启动与结果回调
        return ((ActivityResultCaller) context).registerForActivityResult(new ResultContract(ResultContract.PICTURE_SELECT), result -> {
            Log.e(TAG, "相册调用返回啦");
            String imagePath = null;
            if (result == null) {
                return;
            }
            Uri uri = result.getData();
            if (DocumentsContract.isDocumentUri(context, uri)) {
                // 如果是document类型的Uri，则通过document id处理
                String docId = DocumentsContract.getDocumentId(uri);
                if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                    String id = docId.split(":")[1];
                    // 解析出数字格式的id
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content: //downloads/public_downloads"), Long.parseLong(docId));
                    imagePath = getImagePath(context, contentUri, null);
                }
            } else if ("content".equalsIgnoreCase(uri.getScheme())) {
                // 如果是content类型的Uri，则使用普通方式处理
                imagePath = getImagePath(context, uri, null);
            } else if ("file".equalsIgnoreCase(uri.getScheme())) {
                // 如果是file类型的Uri，直接获取图片路径即可
                imagePath = uri.getPath();
            }
            Bitmap bitmap;
            bitmap = BitmapFactory.decodeFile(imagePath);
            if (bitmap != null) {
                fallbackAction.accept(new BitmapBundle(imagePath, bitmap));
            }
        });
    }


    @SuppressLint("Range")
    private static String getImagePath(Context context, Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = context.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
}
